<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\home\controller;

/**
 * Description of ScancodeController
 *
 * @author Administrator
 */
use think\Db;

class ScancodeController extends BaseController{
    //put your code here
    /**
     * 处理扫码数据
     */
    public function index(){
        var_dump(session('userinfo'));
    }
    
    /**
     * 验证二维码数据有效性
     */
    private function check_data(){
        
    }
    
    /**
     * 扫码记录
     */
    public function do_scancode(){
        $cardnum = input('post.cardnum','0328109999');
        if(empty($cardnum)) return json (['code'=>0,'msg'=>'无效的二维码信息','data'=>[]]); 
        $db = db('cards');
        $card = $db->where(['card_num'=>$cardnum])->find();
        if(empty($card)) return json (['code'=>0,'msg'=>'无开卡记录','data'=>[]]);
        $userid = $this->userinfo['user_id'];#获取当前登录核销人的用户id
//        $sql = 'select a.user_id,a.supplier_id,a.is_delete,a.is_main,s.name as supplier_name,s.preview,s.address,s.user_id as supplier_userid,s.type from fanwe_supplier_account as a inner join fanwe_supplier as s on s.id = a.supplier_id where a.user_id = '.$userid.' limit 0,1';
        $sql = 'select a.user_id,a.supplier_id,a.is_delete,a.is_main,s.name as supplier_name,s.preview,s.address,s.user_id as supplier_userid,s.type,u.user_name,u.sex,u.real_name from  fanwe_supplier as s inner join fanwe_supplier_account as a on s.id = a.supplier_id inner join fanwe_user as u on a.user_id = u.id where a.user_id = '.$userid.' limit 0,1';
        $seller = $db->query($sql);
        #验证订单有效性
//        if(!$this->check_order($card['order_id'])) return json (['code'=>0,'msg'=>'无效的二维码信息','data'=>[],'jump'=>'scancode']);
        #验证当前核销人所扫二维码与店铺是否一致
        if(empty($seller)){
            session('userinfo',null);
            return json ([['code'=>0,'msg'=>'请使用商户账户或子账户登录','data'=>[]]);
        } 
        $seller = $seller[0];
        if($card['seller_id'] != $seller['supplier_id']) return json (['code'=>0,'msg'=>'不是本店二维码，无权认证','data'=>[]]);
        #验证卡种类是否为健身卡
        if($card['type'] != 1 && $card['shop_type'] != 1) return json (['code'=>0,'msg'=>'不是健身卡','data'=>[]]);
        #验证卡状态
        if($card['status'] != 1) return json (['code'=>0,'msg'=>'健身卡过期或卡异常','data'=>[]]);
        #验证卡 剩余有效次数 动态验证
        if($card['vip_card_type'] == 1){
            #天数
            if($card['end_time'] < time()){
                return json (['code'=>0,'msg'=>'健身卡已过期','data'=>[]]);
            }
        }elseif($card['vip_card_type'] == 2){
            #次数
            if($card['times']>= $card['number']){
                return json (['code'=>0,'msg'=>'健身卡次数使用完毕','data'=>[]]);
            }
        }
        #校验成功后 更新健身记录 连接mongo
        $mongodb = db('students', 'database_mg');
        $last_log = $mongodb->table('student')->order('_id', 'desc')->find();
        if(empty($last_id)) $id = 1;
        else
        $id = $last_id['_id'] += 1;
        $user_last_log = $mongodb->table('student')->where(['user_id'=>$card['user_id']])->order('_id','desc')->find();
        if (!empty($user_last_log)) {
            #如果十五分钟内再次扫描则提示已打卡
            if(($user_last_log['start_time']+1800) > time()){
                return json (['code'=>0,'msg'=>'短时间内不能重复打卡','data'=>[]]);
            }
        }
        $param = [
            '_id' => $id,
            'user_id' => $data['user_id'],
            'user_name' => $data['user_name'],
            'supplier_name' => $data['supplier_name'],
            'supplier_id' => $data['supplier_id'],
            'card_num' => $card['card_num'],
            'job' =>'',
            'clerk_id' => $this->userinfo['user_id'],
            'start_time' => time(),
            'status' => 1
        ];
        $data = $mongodb->table('student')->insert($param);
        $this->insert_mongo_log($seller);
        #更新次数 当前卡的使用次数
        $res = $db->where(['card_num'=>$card['card_num']])->setInc('times',1);
        return json(['code'=>1,'msg'=>'认证成功']);
        // dump($data);
        // $count = $mongodb->table('student')->group('user_id');
        
        // dump($count);  

    }
    
    protected function check_order($order_id){
        $orders = db()->table('fanwe_order')->where(['id'=>$order_id])->find();
        if(empty($orders)) return false;
        return true;
    }


    /**
     * 健身码验证
     */
    public function gym_code(){
        var_dump(parse_url(url()));
    }


    /**
     * 记录扫描日志
     * @return [type] [description]
     */
    protected function insert_mongo_log($card,$data){
        $mongodb = db('students', 'database_mg');
        $last_id = $mongodb->table('student')->order('_id', 'desc')->find();
        if(empty($last_id)) $id = 1;
        else
        $id = $last_id['_id'] += 1;
        $param = [
            '_id' => $id,
            'user_id' => $data['user_id'],
            'user_name' => $data['user_name'],
            'supplier_name' => $data['supplier_name'],
            'supplier_id' => $data['supplier_id'],
            'card_num' => $card['card_num'],
            'job' =>'',
            'clerk_id' => $this->userinfo['user_id'],
            'start_time' => date('Y-m-d H:i:s',time()),
            'status' => 1
        ];
        $data = $mongodb->table('student')->insert($param);
        if($data) return true; else return false;
    }    
}
